package com.example.projectmanagement.controller;

import com.example.projectmanagement.model.User;
import com.example.projectmanagement.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/study")
@CrossOrigin
public class StudyController {

    @Autowired
    private UserService userService;

    /**
     * 获取学生列表（按学习积分排序）
     */
    @GetMapping("/students")
    public ResponseEntity<Page<User>> getStudents(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false, defaultValue = "studyPoints") String sortField,
            @RequestParam(required = false, defaultValue = "desc") String sortOrder) {
        
        // 创建排序对象
        Sort sort = Sort.by(Sort.Direction.fromString(sortOrder), sortField);
        Pageable pageable = PageRequest.of(page, size, sort);
        
        Page<User> students;
        if (keyword != null && !keyword.isEmpty()) {
            students = userService.searchStudents(keyword, pageable);
        } else {
            students = userService.getAllStudents(pageable);
        }
        
        return ResponseEntity.ok(students);
    }
}